'''
Created on Mar 1, 2014

@author: chunhuiluo
'''
from django.core.urlresolvers import reverse, resolve
from api.middlewares import ThreadLocal
from jfpal.generics import JSONResponse
from django.db import models
from django.db.models.query import QuerySet
from api import serializers
from django.shortcuts import render as django_render


def api_html(request):
    return django_render(request, 'api/index.html')

'''
Example: 
 http://localhost:8000/api?r=store.tinyshop.detail&tinyshop_id=1
'''
def api_view(request):
    api = request.GET.get('r')
    if api is None:
        return error('paremeter error')
    url = reverse(api)
    func, args, kwargs = resolve(url)
    return func(request, *args, **kwargs)

def api_doc(request):
    return api_html(request)

def _serialize(data, request=None):
    if isinstance(data, models.Model):
        model_class_name = data.__class__.__name__
        serilizer_class_name = "%sSerializer" % model_class_name
        class_ = getattr(serializers, serilizer_class_name)
        serializer = class_(data, context={'request': request})
        return serializer.data
    elif isinstance(data, QuerySet):
        return [_serialize(i, request) for i in data]
    elif isinstance(data, dict):
        return {k: _serialize(v, request) for k, v in data.iteritems()}
    else:
        return data


def render(data):
    request = ThreadLocal.get_current_request()
    context = {'success': True, 'msg':'', 'r': request.REQUEST.get('r',''), 'sign': request.REQUEST.get('sign','')}
    data.update(context)
    s = _serialize(data, request)
    return  JSONResponse(s)

def error(message, data={}):
    request = ThreadLocal.get_current_request()
    context = {'success': False, 'msg': message, 'r': request.REQUEST.get('r',''), 'sign': request.REQUEST.get('sign','')}
    data.update(context)
    s = _serialize(data, request)
    return  JSONResponse(s)
